package rpc.gray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import rpc.route.RoutePlugin;

import java.net.InetSocketAddress;
import java.util.Map;

@Component
public class GrayPluginImpl implements GrayPlugin {
    @Autowired
    Map<InetSocketAddress, InetSocketAddress> grayNodes;

    @Value("client.address")
    String clientAddressString;
    InetSocketAddress clientAddress;
    {
        String[] clientAddressArray = clientAddressString.split(":");
        if (clientAddressArray.length == 2) { // Should check IP and port
            String host = clientAddressArray[0];
            int port = Integer.parseInt(clientAddressArray[1]);
            clientAddress = new InetSocketAddress(host, port);
        }
    }

    @Override
    public InetSocketAddress grayPublish(InetSocketAddress address) {
        InetSocketAddress grayAddress = grayNodes.get(clientAddress);
        if (grayAddress == null || grayAddress == address){
            return address;
        }
        return grayPublish(address);
    }
}
